import json
from sqlalchemy.ext.asyncio import AsyncSession

from config.constant import CommonConstant
from config.enums import RedisInitKeyConfig
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_basics.dao.thesaurus_dao import ThesaurusDao, ThesaurusDataDao
from module_basics.entity.vo.thesaurus_vo import ThesaurusQueryModel, ThesaurusModel, ThesaurusDataQueryModel, \
    ThesaurusDataPageQueryModel, ThesaurusDataModel
from utils.common_util import CamelCaseUtil


class ThesaurusService:
    """
     词库管理模块服务层
     """

    @classmethod
    async def get_thesaurus_list_services(
            cls, query_db: AsyncSession, query_object: ThesaurusQueryModel, is_page: bool = False
    ):
        """
        获取词库列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 岗位列表信息对象
        """
        thesaurus_list_result = await ThesaurusDao.get_thesaurus_list(query_db, query_object, is_page)

        return thesaurus_list_result

    @classmethod
    async def add_thesaurus_catalogue_services(cls, request, query_db, page_object):
        """
        新增专业词库目录信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 新增专业词库目录对象
        :return: 新增字典类型校验结果
        """
        if not await cls.check_thesaurus_catalogue_unique_services(query_db, page_object):
            raise ServiceException(message=f'新增字典{page_object.thesaurus_type}失败，字典类型已存在')
        else:
            try:
                await ThesaurusDao.add_thesaurus_catalogue_dao(query_db, page_object)
                await query_db.commit()
                result = dict(is_success=True, message='新增成功')
            except Exception as e:
                await query_db.rollback()
                raise e

        return CrudResponseModel(**result)

    @classmethod
    async def check_thesaurus_catalogue_unique_services(cls, query_db: AsyncSession, page_object: ThesaurusModel):
        """
        校验专业词库目录类型是否唯一service

        :param query_db: orm对象
        :param page_object: 字典类型对象
        :return: 校验结果
        """
        thesaurus_id = -1 if page_object.thesaurus_id is None else page_object.thesaurus_id
        thesaurus_catalogue = await ThesaurusDao.get_thesaurus_catalogue_detail_by_info(
            query_db, ThesaurusModel(thesaurus_type=page_object.thesaurus_type)
        )
        if thesaurus_catalogue and thesaurus_catalogue.thesaurus_id != thesaurus_id:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE

    @classmethod
    async def edit_thesaurus_catalogue_services(cls, request, query_db, page_object):
        """
        编辑专业词库目录信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 编辑字典类型对象
        :return: 编辑字典类型校验结果
        """
        edit_thesaurus_catalogue = page_object.model_dump(exclude_unset=True)
        thesaurus_catalogue_info = await cls.thesaurus_catalogue_detail_services(query_db, page_object.thesaurus_id)
        if thesaurus_catalogue_info.thesaurus_id:
            if not await cls.check_thesaurus_catalogue_unique_services(query_db, page_object):
                raise ServiceException(message=f'修改字典{edit_thesaurus_catalogue.thesaurus_type}失败，字典类型已存在')
            else:
                try:
                    query_thesaurus_data = ThesaurusDataPageQueryModel(thesaurus_type=thesaurus_catalogue_info.
                                                                       thesaurus_type)
                    thesaurus_data_list = await ThesaurusDataDao.get_thesaurus_data_list(query_db, query_thesaurus_data,
                                                                                         is_page=False)
                    if thesaurus_catalogue_info.thesaurus_type != page_object.thesaurus_type:
                        for thesaurus_data in thesaurus_data_list:
                            edit_thesaurus_data = ThesaurusDataModel(
                                dataId=thesaurus_data['dataId'],
                                thesaurusType=page_object.thesaurus_type,
                                updateBy=page_object.update_by,
                            ).model_dump(exclude_unset=True)
                            await ThesaurusDataDao.edit_thesaurus_data_dao(query_db, edit_thesaurus_data)
                    await ThesaurusDao.edit_thesaurus_catalogue_dao(query_db, edit_thesaurus_catalogue)
                    await query_db.commit()
                    return CrudResponseModel(is_success=True, message='更新成功')
                except Exception as e:
                    await query_db.rollback()
                    raise e
        else:
            raise ServiceException(message='词库类型不存在')

    @classmethod
    async def thesaurus_catalogue_detail_services(cls, query_db: AsyncSession, thesaurus_id: int):
        """
        获取专业词库目录详细信息service

        :param query_db: orm对象
        :param thesaurus_id: 字典类型id
        :return: 字典类型id对应的信息
        """
        thesaurus_catalogue = await ThesaurusDao.get_thesaurus_catalogue_detail_by_id(query_db,
                                                                                      thesaurus_id=thesaurus_id)
        if thesaurus_catalogue:
            result = ThesaurusModel(**CamelCaseUtil.transform_result(thesaurus_catalogue))
        else:
            result = ThesaurusModel(**dict())

        return result

    @classmethod
    async def delete_thesaurus_catalogue_services(cls, request, query_db, page_object):
        """
        删除字典类型信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 删除字典类型对象
        :return: 删除字典类型校验结果
        """
        if page_object.thesaurus_ids:
            thesaurus_id_list = page_object.thesaurus_ids.split(',')
            try:
                for thesaurus_id in thesaurus_id_list:
                    thesaurus_catalogue_into = await cls.thesaurus_catalogue_detail_services(query_db,
                                                                                             int(thesaurus_id))
                    if (await ThesaurusDataDao.count_thesaurus_data_dao(query_db,
                                                                        thesaurus_catalogue_into.thesaurus_type)) > 0:
                        raise ServiceException(message=f'{thesaurus_catalogue_into.thesaurus_name}已分配，不能删除')
                    await ThesaurusDao.delete_thesaurus_catalogue_dao(query_db,
                                                                      ThesaurusModel(thesaurusId=int(thesaurus_id)))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入字典类型id为空')


class ThesaurusDataService:
    """
     词库管理模块服务层
     """

    @classmethod
    async def get_thesaurus_data_list_services(
            cls, query_db: AsyncSession, query_object: ThesaurusDataQueryModel, is_page: bool = False
    ):
        """
        获取词库列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 岗位列表信息对象
        """
        thesaurus_data_list_result = await ThesaurusDataDao.get_thesaurus_data_list(query_db, query_object, is_page)

        return thesaurus_data_list_result

    @classmethod
    async def add_thesaurus_data_services(cls, request, query_db, page_object):
        """
        新增字典数据信息service

        :param request: Request对象
        :param query_db: orm对象
        :param page_object: 新增岗位对象
        :return: 新增字典数据校验结果
        """
        if not await cls.check_thesaurus_data_unique_services(query_db, page_object):
            raise ServiceException(
                message=f'新增字典数据{page_object.dict_label}失败，{page_object.dict_type}下已存在该字典数据'
            )
        else:
            try:
                await ThesaurusDataDao.add_thesaurus_data_dao(query_db, page_object)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='新增成功')
            except Exception as e:
                await query_db.rollback()
                raise e

    @classmethod
    async def check_thesaurus_data_unique_services(cls, query_db, page_object):
        """
         校验专业词库数据是否唯一service

         :param query_db: orm对象
         :param page_object: 字典数据对象
         :return: 校验结果
         """
        data_id = -1 if page_object.dict_code is None else page_object.dict_code
        thesaurus_data = await ThesaurusDataDao.get_thesaurus_data_detail_by_info(query_db, page_object)
        if thesaurus_data and thesaurus_data.data_id != data_id:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE

    @classmethod
    async def edit_thesaurus_data_services(cls, request, query_db, page_object):
        """
       编辑字典数据信息service

       :param request: Request对象
       :param query_db: orm对象
       :param page_object: 编辑字典数据对象
       :return: 编辑字典数据校验结果
       """
        edit_data_type = page_object.model_dump(exclude_unset=True)
        dict_data_info = await cls.thesaurus_data_detail_services(query_db, page_object.dict_code)
        if dict_data_info.dict_code:
            if not await cls.check_thesaurus_data_unique_services(query_db, page_object):
                raise ServiceException(
                    message=f'新增字典数据{page_object.dict_name}失败，{page_object.dict_name}下已存在该字典数据'
                )
            else:
                try:
                    await ThesaurusDataDao.edit_thesaurus_data_dao(query_db, edit_data_type)
                    await query_db.commit()
                    return CrudResponseModel(is_success=True, message='更新成功')
                except Exception as e:
                    await query_db.rollback()
                    raise e
        else:
            raise ServiceException(message='字典数据不存在')

    @classmethod
    async def delete_thesaurus_data_services(cls, request, query_db, page_object):
        """
       删除专业词酷数据信息service

       :param request: Request对象
       :param query_db: orm对象
       :param page_object: 删除字典数据对象
       :return: 删除字典数据校验结果
       """
        if page_object.dict_codes:
            data_id_list = page_object.data_ids.split(',')
            try:
                delete_dict_type_list = []
                for data_id in data_id_list:
                    thesaurus_data = await cls.thesaurus_data_detail_services(query_db, int(data_id))
                    await ThesaurusDataDao.delete_thesaurus_data_dao(query_db, ThesaurusDataModel(dataId=data_id))
                    delete_dict_type_list.append(thesaurus_data.dict_type)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='    传入字典数据id为空')

    @classmethod
    async def thesaurus_data_detail_services(cls, query_db, data_id):
        """
        获取专业词酷数据详细信息service

        :param query_db: orm对象
        :param data_id: 字典数据id
        :return: 字典数据id对应的信息
        """
        thesaurus_data = await ThesaurusDataDao.get_thesaurus_data_detail_by_id(query_db, data_id=data_id)
        if thesaurus_data:
            result = ThesaurusDataModel(**CamelCaseUtil.transform_result(thesaurus_data))
        else:
            result = ThesaurusDataModel(**dict())

        return result
